package com.winning.pmph.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winning.pmph.entity.ExerciseBook;
import com.winning.pmph.entity.ExerciseEntry;
import com.winning.pmph.entity.ExerciseGroup;
import com.winning.pmph.entity.Journal;
import com.winning.pmph.service.ExerciseBookService;
import com.winning.pmph.service.ExerciseEntryService;
import com.winning.pmph.service.ExerciseGroupService;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.ExecutorServiceFactory;
import com.winning.pmph.utils.UploadFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

@Api(value = "知识资源管理/试题管理/试题图书")
@RestController
@RequestMapping("/pmph/action/exerciseBook")
public class ExerciseBookCtrl {
    @Resource
    private ExerciseBookService exerciseBookService;
    @Resource
    private ExerciseEntryService exerciseEntryService;
    @Resource
    private ExerciseGroupService exerciseGroupService;

    @ApiOperation(value = "selectPage", notes = "按条件查询page", tags = "1/2")
    @GetMapping("selectPage")
    public Page<ExerciseBook> selectPage(ExerciseBook exerciseBook) {
        Page<ExerciseBook> page = new Page<>(exerciseBook.getCurrentPage(), exerciseBook.getPageSize());
        LambdaQueryWrapper<ExerciseBook> queryWrapper = Wrappers.lambdaQuery(ExerciseBook.class).eq(ExerciseBook::getStatus, exerciseBook.getStatus());
        if (StringUtils.isNotEmpty(exerciseBook.getName())) {
            queryWrapper.like(ExerciseBook::getName, exerciseBook.getName());
        }
        if (StringUtils.isNotEmpty(exerciseBook.getIsbn())) {
            queryWrapper.like(ExerciseBook::getIsbn, exerciseBook.getIsbn());
        }
        if (Objects.nonNull(exerciseBook.getImportStatus())) {
            queryWrapper.eq(ExerciseBook::getImportStatus, exerciseBook.getImportStatus());
        }
        if (Objects.nonNull(exerciseBook.getVersion())) {
            queryWrapper.eq(ExerciseBook::getVersion, exerciseBook.getVersion());
        }
        if (CollectionUtils.isNotEmpty(exerciseBook.getImportDateRange())) {
            queryWrapper.ge(ExerciseBook::getImportDate, exerciseBook.getImportDateRange().get(0));
            queryWrapper.le(ExerciseBook::getImportDate, exerciseBook.getImportDateRange().get(1));
        }
        if (StringUtils.isNotEmpty(exerciseBook.getCreatedBy())) {
            queryWrapper.eq(ExerciseBook::getCreatedBy, exerciseBook.getCreatedBy());
        }
        queryWrapper.orderByDesc(ExerciseBook::getImportDate).orderByDesc(ExerciseBook::getId);
        exerciseBookService.page(page, queryWrapper);
        return page;
    }

    @ApiOperation(value = "importZip", notes = "上传并解析题库压缩包")
    @PostMapping("importZip")
    public String importZip(MultipartFile file, String id) {
        String path = ApplicationContextUtil.BASE_DOWN_FORDER + "book/";
        String name = UploadFileUtil.uploadFile(file, path, false);
        // 文件上传成功后,开始解析,另起线程解析zip包
        // 修改当前题库导入状态
        ExerciseBook exerciseBook = exerciseBookService.getById(id);
        if (Objects.isNull(exerciseBook)) {
            exerciseBook = new ExerciseBook();
            exerciseBook.setId(StringUtils.defaultIfBlank(id, IdWorker.getIdStr()));
        }
        exerciseBook.setName(StringUtils.removeEnd(name, ".zip"));
        exerciseBook.setFilePath(path + name);
        exerciseBook.setImportStatus(Journal.STATUS_IMPORTING);
        exerciseBook.setFailureReason(null);
        exerciseBookService.saveOrUpdate(exerciseBook);
        // 另起线程解析zip包
        ExerciseBook finalExerciseBook = exerciseBook;
        ExecutorServiceFactory.getInstance().submit(() -> {
            try {
                exerciseBookService.importBook(finalExerciseBook);
            } catch (RuntimeException e) {
                finalExerciseBook.setImportStatus(Journal.STATUS_IMPORT_FAILURE);
                finalExerciseBook.setFailureReason(e.getMessage());
                exerciseBookService.saveOrUpdate(finalExerciseBook);
            }
        });
        return "正在导入中, 请稍后查看导入结果";
    }


    @ApiOperation(value = "deleteById", notes = "删除题库")
    @PostMapping("deleteById")
    public void deleteById(@RequestBody ExerciseBook exerciseBook) {
        exerciseBookService.deleteById(exerciseBook.getId());
    }

    @ApiOperation(value = "updateById", notes = "修改图书")
    @PostMapping("updateById")
    public void updateById(@RequestBody ExerciseBook exerciseBook) {
        exerciseBookService.updateById(exerciseBook);
    }

    @ApiOperation(value = "selectExerciseGroupPage", notes = "详情, 查询试题page接口")
    @GetMapping("selectExerciseGroupPage")
    public Page<ExerciseGroup> selectExerciseGroupPage(ExerciseGroup exerciseGroup) {
        return exerciseBookService.selectExerciseGroupPage(exerciseGroup);
    }

    @ApiOperation(value = "deleteExerciseGroup", notes = "删除试题")
    @PostMapping("deleteExerciseGroup")
    public void deleteExerciseGroup(@RequestBody ExerciseGroup exerciseGroup) {
        exerciseBookService.deleteExerciseGroup(exerciseGroup);
    }

    @ApiOperation(value = "selectExerciseEntryListByGroupId", notes = "试题编辑, 详情, 根据groupId, 查询试题集合")
    @GetMapping("selectExerciseEntryListByGroupId")
    public List<ExerciseEntry> selectExerciseEntryListByGroupId(String exerciseGroupId) {
        return exerciseEntryService.lambdaQuery().eq(ExerciseEntry::getGroupId, exerciseGroupId).list();
    }

    @ApiOperation(value = "updateExerciseGroup", notes = "试题编辑, 保存接口")
    @PostMapping("updateExerciseGroup")
    public void updateExerciseGroup(@RequestBody ExerciseGroup exerciseGroup) {
        exerciseGroupService.updateExerciseGroup(exerciseGroup);
    }

    @ApiOperation(value = "releaseExerciseBook", notes = "试题发布, 单条")
    @PostMapping("releaseExerciseBook")
    public void releaseExerciseBook(@RequestBody ExerciseBook exerciseBook) {
        exerciseBookService.releaseExerciseBook(exerciseBook);
    }

    @ApiOperation(value = "releaseExerciseBookList", notes = "试题图书发布, 多条")
    @PostMapping("releaseExerciseBookList")
    public void releaseExerciseBook(@RequestBody List<String> exerciseBookIdList) {
        exerciseBookService.releaseExerciseBookList(exerciseBookIdList);
    }

}